# 功能模块：3D引擎鼠标事件类
# 作者：dl
# 描述：鼠标点击事件单独封装

import vtk

from vtkmodules.vtkInteractionStyle import vtkInteractorStyleMultiTouchCamera
from vtkmodules.vtkRenderingCore import (
    vtkHardwareSelector
)

from vtkmodules.vtkCommonDataModel import (
    vtkSelectionNode
)

from visualizationCom.tools.color import hex_to_rgba
import random
import nest_asyncio
nest_asyncio.apply()


# pick scene-node
class SceneNodePicker(vtkHardwareSelector):
    def __init__(self) -> None:
        pass

    def Pick(self, x, y):
        self.SetArea(x, y, x, y)
        res = self.Select()
        if res.GetNumberOfNodes() > 0:
            # only get the first one...
            node = res.GetNode(0)
            prop = node.GetProperties()
            id = node.GetSelectionList().GetValue(0)

            key = vtkSelectionNode.PROP()
            if prop.Has(key):
                actor = key.Get(prop)
                # check if it is an instance actor...
                if hasattr(actor, 'scene'):
                    return actor, id
        return None, None

# 鼠标控制


class mouseInteractorEvent(vtkInteractorStyleMultiTouchCamera):
    def __init__(self, parent, webState, webCtrl):
        self.parent = parent
        self.webState = webState
        self.webCtrl = webCtrl

        # 注册事件
        self.AddObserver("LeftButtonPressEvent", self.onLeftButtonDown)

        # 记录上一次左键按下的时间戳和位置
        self.last_left_button_press_time = 0.0
        self.last_left_button_press_position = (0, 0)

        # 石老师所写的外轮廓边缘描绘示例代码
        self.picker = SceneNodePicker()
        self.lastPick = None
        # renderers
        self.outline = None

    def SetDefaultRenderer(self, renderer):
        self.picker.SetRenderer(renderer)
        super().SetDefaultRenderer(renderer)

    def SetOutlineRenderer(self, renderer):
        self.outline = renderer

    # 鼠标左键
    def onLeftButtonDown(self, obj, event):
        current_time = vtk.vtkTimerLog.GetUniversalTime()
        current_position = self.GetInteractor().GetEventPosition()

        # 处理单击和双击事件
        if (
            current_time - self.last_left_button_press_time < 0.5 and
            current_position == self.last_left_button_press_position
        ):
            print("Double Click")
        else:
            self.last_left_button_press_time = current_time
            self.last_left_button_press_position = current_position

            actor, id = self.picker.Pick(
                current_position[0], current_position[1])
            if actor == None or id == None:
                self.outline.Clear()
                self.lastPick = None
            else:
                scene = actor.scene
                node = actor.GetNode(id)
                self.outline.Clear()
                self.outline.AddSceneNode(scene, node)
                self.lastPick = [scene, node]

            self.OnLeftButtonDown()
            self.webCtrl.view_update()
            self.webCtrl.view_update()
            return
